/*
 * Copyright @ 2022 bingye
 * com.iflytek.zhcs.yjsqd.portal.config 17:16
 * All right reserved.
 */

package com.example.demo.configuration;


import com.example.demo.utils.CommonResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @desc:统一返回结果对象
 * @author: weili23
 * @params
 * @Date: 2024/5/8 9:37
 * @version: 1.0
 */
@RestControllerAdvice(basePackages = "com.example.demo")
public class CommonResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object object, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if(object instanceof CommonResult || object instanceof ResponseEntity){
            return object;
        }else{
            if(object instanceof String){
                return objectMapper.writeValueAsString(CommonResult.success(object));
            }
        }
        return CommonResult.success(object);
    }
}
